<template>
    <div class="rate">
        <span v-for="index in currentRate" :key="'active-' + index" class="star">
            <img class="xingxing" src="/static/xhong.png" />
        </span>
    </div>
</template>

<script>
export default {
    name: 'Rate',
    data() {
        return {
            currentRate: 0, // 当前评分
        }
    },
    props: {
        modelValue: {
            type: [Number, String],
            default: 0,
            validator: (value) => {
                // 验证传入的值是否有效
                const num = Number(value);
                return !isNaN(num) && num >= 0 && num <= 5;
            }
        }
    },
    watch: {
        modelValue: {
            immediate: true,
            handler(newVal) {
                // 处理字符串转换为数字的逻辑
                if (typeof newVal === 'string') {
                    // 去除前后空格
                    const trimmedVal = newVal.trim();
                    // 如果是空字符串，设为0
                    if (trimmedVal === '') {
                        this.currentRate = 0;
                        return;
                    }
                    // 尝试转换为数字
                    const num = Number(trimmedVal);
                    // 确保转换后的数字在0-5范围内
                    this.currentRate = isNaN(num) ? 0 : Math.min(5, Math.max(0, Math.round(num)));
                } else {
                    // 已经是数字类型，直接使用（确保在0-5范围内）
                    this.currentRate = Math.min(5, Math.max(0, Math.round(newVal)));
                }
            }
        }
    }
}
</script>

<style scoped lang="less">
.xingxing {
    width: 40px;
    display: block;
    margin: 0 8PX;
}

.rate {
    display: inline-flex;
    margin-top: 5px;

    .star {
        color: #ccc;
        font-size: 30px;
    }

    .star.active {
        color: #F40C0C;
    }
}
</style>